package com.ey.system.admin.module.generator.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.template.*;
import com.ey.system.admin.module.generator.config.GenConfig;
import com.ey.system.admin.module.generator.service.IGenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuang_ming_nan
 * @since 2019/9/28 0:12
 */
@Slf4j
@Service
public class GenServiceImpl implements IGenService {

    @Autowired
    private GenConfig genConfig;

    @Override
    public void gen(String tableName) {
        genController("user");
    }

    public void genController(String tableName) {
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("generator/template",
                TemplateConfig.ResourceMode.CLASSPATH));
        Template template = engine.getTemplate("admin/Controller.ftl");

        String projectPath = System.getProperty("user.dir") + File.separator + "ey-system-admin";
        String packagePath = projectPath + File.separator + "src" +File.separator+ "main" + File.separator + "java" + File.separator;
        packagePath = packagePath + File.separator + "com/ey/system/admin/module/admin/controller";

        File file = new File(packagePath + File.separator
                + tableName.substring(0,1).toUpperCase().concat(tableName.substring(1))
                + "Controller.java");

        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableName);
        map.put("author", genConfig.getAuthor());
        try {
            genFile(file, template, map);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("生成controller代码出错", e);
            throw new RuntimeException(e);
        }
    }

    public static void genFile(File file, Template template, Map<String,Object> map) throws IOException {
        // 生成目标文件
        Writer writer = null;
        try {
            FileUtil.touch(file);
            writer = new FileWriter(file);
            template.render(map, writer);
        } catch (TemplateException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                writer.close();
            }

        }
    }
}
